use axum::{response::IntoResponse, Form};
use tower_cookies::{Cookie, Cookies};

use crate::{config::AppContext, domain::reply::Reply, service::reply_service, ApiResponse};

pub async fn save(cookies: Cookies, reply: Form<Reply>) -> impl IntoResponse {
    let mut reply = reply.0;
    reply.id = None;
    let reply_id = reply_service::save(&mut reply).await.unwrap();

    let cookie = Cookie::new("username", reply.pname.unwrap_or_default());
    cookies.add(cookie);

    ApiResponse::from(reply_id)
}

pub async fn del(reply: Form<Reply>) -> impl IntoResponse {
    let reply = reply.0;
    assert!(reply.id.unwrap_or_default() > 0, "参数错误");
    let _ = reply_service::delete(reply).await;
    ApiResponse::from(1)
}

pub async fn audit(reply: Form<Reply>) -> impl IntoResponse {
    let mut reply = reply.0;
    assert!(reply.id.unwrap_or_default() > 0, "参数错误");
    let rbatis = AppContext::rbatis();
    reply.isn = Some(0);
    let _ = Reply::update_by_column_skip(rbatis, &reply, "id", true).await;
    ApiResponse::from(1)
}
pub async fn reply(reply: Form<Reply>) -> impl IntoResponse {
    let reply = reply.0;
    assert!(reply.id.unwrap_or_default() > 0, "参数错误");
    let rbatis = AppContext::rbatis();
    let _ = Reply::update_by_column_skip(rbatis, &reply, "id", true)
        .await
        .unwrap();
    ApiResponse::from(1)
}
